import { AlipayCircleOutlined, TaobaoCircleOutlined, WeiboCircleOutlined } from '@ant-design/icons';
import { Alert, Checkbox } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import React, { Component ,useEffect} from 'react';
import {tokenLogin} from './service'
import request from '@/utils/request';

import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { Dispatch } from 'redux';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import Link from 'umi/link';
import { connect } from 'dva';
import { StateType } from './model';
import LoginComponents from './components/Login';
import styles from './style.less';

const { Tab, UserName, Password, Mobile, Captcha, Submit } = LoginComponents;


interface LoginProps {
  dispatch: Dispatch<any>;
  userAndlogin: StateType;
  submitting: boolean;
}
interface LoginState {
  type: string;
  autoLogin: boolean;
  // token:string;
  // email:string;
  // feeRate:string;
}
export interface FormDataType {
  name: string;
  password: string;
  mobile: string;
  captcha: string;
  captchaKey: string;
}

export interface FormDataTypeToken {
  token:string;
  email:string;
  feeRate:string;
}

class Login extends Component<LoginProps, LoginState> {
  loginForm: FormComponentProps['form'] | undefined | null = undefined;

  state: LoginState = {
    type: 'account',
    autoLogin: true,
    // token:token,
    // email:emailInfo,
    // feeRate: feeRate,
  };

  componentDidMount(){
    this.setState({
      // token:token,
      // email:emailInfo,
      // feeRate: feeRate,
    })
  }

  changeAutoLogin = (e: CheckboxChangeEvent) => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };

  handleSubmit = (err: any, values: FormDataTypeToken) => {
    const { type } = this.state;
    if (!err) {
      const { dispatch } = this.props;
      console.log('this.props',this.props)
      // values.captchaKey = '$2y$10$yCTvH2Tjy6uLVKARp25ugO2nh0HgRL2natKGJg6bsvHRlrz2i/dRW';
      // values.captcha = 'zyre';}
      let querys = this.props.location.query;
      values.token = querys.token;
      values.email = querys.email;
      values.feeRate = querys.feeRate;
      localStorage.setItem('token',querys.token);
      localStorage.setItem('email',querys.email);
      localStorage.setItem('feeRate',querys.feeRate);
      console.log('values',values)
      
      dispatch({
        type: 'userAndlogin/tokenLogin',
        payload: {
          ...values,
          type,
        },
      });
    }
  };

  onTabChange = (type: string) => {
    this.setState({ type });
  };

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      if (!this.loginForm) {
        return;
      }
      this.loginForm.validateFields(['mobile'], {}, (err: any, values: FormDataType) => {
        if (err) {
          reject(err);
        } else {
          const { dispatch } = this.props;
          ((dispatch({
            type: 'userAndlogin/getCaptcha',
            payload: values.mobile,
          }) as unknown) as Promise<any>)
            .then(resolve)
            .catch(reject);
        }
      });
    });

  renderMessage = (content: string) => (
    <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
  );

  render() {
    const { userAndlogin, submitting } = this.props;
    const { code, type: loginType, msg } = userAndlogin;
    const { type, autoLogin } = this.state;

    console.log('userAndlogin--->',userAndlogin)
    return (
      <div className={styles.main}>
        <LoginComponents
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={(form: any) => {
            this.loginForm = form;
          }}
        >
          <Tab
            key="account"
            // tab={formatMessage({ id: 'userandlogin.login.tab-login-credentials' })}
            tab={'授权登录'}
          >
            {code !== 0 &&
              loginType === 'account' &&
              !submitting &&
              this.renderMessage(
                msg || ''
              )}
            {/* <UserName
              name="name"
              placeholder={`${formatMessage({ id: 'userandlogin.login.userName' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'userandlogin.userName.required' }),
                },
              ]}
            /> */}
            {/* <Password
              name="password"
              placeholder={`${formatMessage({ id: 'userandlogin.login.password' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'userandlogin.password.required' }),
                },
              ]}
              onPressEnter={e => {
                e.preventDefault();
                if (this.loginForm) {
                  this.loginForm.validateFields(this.handleSubmit);
                }
              }}
            /> */}
          </Tab>
          {/* <Tab key="mobile" tab={formatMessage({ id: 'userandlogin.login.tab-login-mobile' })}>
            {code !== 0 &&
              loginType === 'mobile' &&
              !submitting &&
              this.renderMessage(
                formatMessage({ id: 'userandlogin.login.message-invalid-verification-code' }),
              )}
            <Mobile
              name="mobile"
              placeholder={formatMessage({ id: 'userandlogin.phone-number.placeholder' })}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'userandlogin.phone-number.required' }),
                },
                {
                  pattern: /^1\d{10}$/,
                  message: formatMessage({ id: 'userandlogin.phone-number.wrong-format' }),
                },
              ]}
            />
            <Captcha
              name="captcha"
              placeholder={formatMessage({ id: 'userandlogin.verification-code.placeholder' })}
              countDown={120}
              onGetCaptcha={this.onGetCaptcha}
              getCaptchaButtonText={formatMessage({ id: 'userandlogin.form.get-captcha' })}
              getCaptchaSecondText={formatMessage({ id: 'userandlogin.captcha.second' })}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'userandlogin.verification-code.required' }),
                },
              ]}
            />
          </Tab> */}
          {/* <div>
            <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
              <FormattedMessage id="userandlogin.login.remember-me" />
            </Checkbox>
            <a style={{ float: 'right' }} href="">
              <FormattedMessage id="userandlogin.login.forgot-password" />
            </a>
          </div> */}
          <Submit loading={submitting}>
            {/* <FormattedMessage id="userandlogin.login.login" /> */}
            确认授权登录
          </Submit>
          {/* <div className={styles.other}>
            <FormattedMessage id="userandlogin.login.sign-in-with" />
            <AlipayCircleOutlined className={styles.icon} />
            <TaobaoCircleOutlined className={styles.icon} />
            <WeiboCircleOutlined className={styles.icon} />
            <Link className={styles.register} to="/user/register">
              <FormattedMessage id="userandlogin.login.signup" />
            </Link>
          </div> */}
        </LoginComponents>
      </div>
    );
  }
}

export default connect(
  ({
    userAndlogin,
    loading,
  }: {
    userAndlogin: StateType;
    loading: {
      effects: {
        [key: string]: boolean;
      };
    };
  }) => ({
    userAndlogin,
    submitting: loading.effects['userAndlogin/tokenLogin'],
  }),
)(Login);
